from django.contrib.auth.backends import ModelBackend
import re
from .models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """重写JWT登录视图"""
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username,
        'success': True
    }


def get_user_by_account(account):
    """通过传入的账号动态获取user模型对象"""
    try:
        if re.match(r'1[3-9]\d{9}$', account):
            # 帐号为手机号
            user = User.objects.get(mobile=account)
        else:
            # 帐号为用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """修改django的认证类，实现多账号登录"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)         # 获取user
        if user and user.check_password(password):        # 判断密码是否一致
            return user         # 返回user

